<template>
  <span
    :class="[styles.module, 'tr-state-label']"
    v-bind="{ ...attrs, ...mappingProps, ...stateStyle }"
    v-show="mappingProps.visible"
    @click="onClickHandler"
    :title="
      mappingProps.showHint
        ? mappingProps.hintMode == 'custom'
          ? mappingProps.hintMsg
          : label
        : null
    "
  >
    {{ label ? label : mappingProps.text }}
  </span>
</template>

<script>
import useMappingProps from 't/common/hooks/useMappingProps';
import { commonProps, createNameSpace } from 't/common/utils';
import { ref, defineComponent, watch, computed } from 'vue';
import styles from './index.module.scss';
import './index.scss';
import { cloneDeep, isNil } from 'lodash';

export default defineComponent({
  name: createNameSpace('state-label'),
  props: {
    ...commonProps,
    icon: String,
    showIcon: Boolean,
    showHint: Boolean,
    hintMode: String,
    hintMsg: String,
    stateRule: {
      type: Array,
      default() {
        return [];
      },
    },
    modelValue: [String, Number, Boolean],
    text: String,
  },
  components: {},
  emits: ['click'],
  setup(props, { attrs, emit, expose, slots }) {
    const [mappingProps, mappingExpose] = useMappingProps(props);
    expose(mappingExpose);
    const label = ref('');
    const stateStyle = ref({});
    function init() {
      stateStyle.value.style = !!window['fas']?.inDesign
        ? {}
        : { ...(attrs.style || []) };
      if (mappingProps.stateRule && mappingProps.stateRule.length > 0) {
        let target = mappingProps.stateRule.find(item => {
          let value = isNil(mappingProps.modelValue)
            ? ''
            : typeof mappingProps.modelValue === 'string'
              ? mappingProps.modelValue
              : mappingProps.modelValue.toString();
          return item.value === value;
        });
        if (target) {
          label.value = window.Funcs
            ? Funcs.GetTerms(target.ValueInfo_label, target.label)
            : target.label;
          stateStyle.value.style['background-color'] = target.bgColor;
          stateStyle.value.style['color'] = target.color;
        } else {
          target = mappingProps.stateRule.find(item => {
            return !item.value;
          });
          if (target) {
            label.value = window.Funcs
              ? Funcs.GetTerms(target.ValueInfo_label, target.label)
              : target.label;
            stateStyle.value.style['background-color'] = target.bgColor;
            stateStyle.value.style['color'] = target.color;
          }
        }
      }
    }
    init();
    function onClickHandler(e) {
      // 事件触发
      emit('click', e);
    }
    watch(
      () => {
        return [mappingProps.modelValue, mappingProps.stateRule];
      },
      (newVal, oldVal) => {
        init();
      },
      { deep: true },
    );
    return { attrs, styles, mappingProps, label, stateStyle };
  },
});
</script>
